package com.bemyapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bemyapp.model.Extract;
import com.bemyapp.mp.MP;
import com.bemyapp.tts.ParrotTTSObserver;
import com.bemyapp.tts.ParrotTTSPlayer;

public class TranslationActivity extends Activity   implements ParrotTTSObserver, OnCompletionListener{
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */

	TextView tvFrench, tvDetails;
	boolean fromRepeat;
	Extract e;

	ParrotTTSPlayer pttsPlayer;
	DBAdapter db;
	int state ; // 0 not started
	// 1 Asking for translate
	// 2 waitin for answer & say "Congratulations" !
	// 3 Real extract


	Handler handler;
	private AsyncTask<Void, Void, Void> currentAsync;
	private WakeLock wl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.translation);

		this.handler = new Handler();
		tvFrench = (TextView)findViewById(R.id.textTranslationFrench);
		tvDetails = (TextView)findViewById(R.id.textTranslationDetails);
		if(this.getIntent().getExtras() != null)
			fromRepeat = this.getIntent().getExtras().getBoolean("repeat");
		else	
			fromRepeat = false;
		db = new DBAdapter(this);
		db.open();

		MP.getInstance().setOnCompletionListener(this);
		
		PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "whereisbryan");
        wl.acquire();
		
	}


	void getExtractAndAskTranslate(){
		state = 1;

		if(fromRepeat)		e = db.getExtractToTranslateAlreadyRepeated();
		else				e = db.getExtractToRepeat(true); 

		handler.post(new Runnable() {

			@Override
			public void run() {
				TranslationActivity.this.findViewById(R.id.layoutTranslation).setBackgroundResource(e.isTranslationDone() ? R.drawable.deja_fait : R.drawable.pas_fait);
				tvFrench.setText(e.getFrench());
				tvFrench.setVisibility(View.VISIBLE);
				tvDetails.setVisibility(View.GONE);
			}
		});



		this.currentAsync = new AsyncTask<Void, Void, Void>(){
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 1000);
				return null;
			}
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				pttsPlayer.play("Traduisez. "+e.getFrench());
			}
		};
		this.currentAsync.execute();
	}

	void waitForAnswer(){
		state=2;

		this.currentAsync = new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 3000);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				pttsPlayer.play("Bravo ! ");
				e.setTranslationDone(true);
				db.extractIsAlreadyTranslated(e.getId());
			}
		};
		this.currentAsync.execute();

	}	

	void getRealExtract(){
		state=3;

		handler.post(new Runnable() {
			@Override
			public void run() {
				tvFrench.setVisibility(View.GONE);
				tvDetails.setVisibility(View.VISIBLE);
				tvDetails.setText(e.getActorName()+" dans "+e.getMovieName()+".");
			}
		});
		e.play(TranslationActivity.this);

	}	

	public void onTTSFinished() {
		if(fromRepeat && state==3){ // time to go back to Repeat
			Intent i = new Intent(this,RepeatActivity.class) ;
			i.putExtra("repeat", true);
			this.startActivity(i);
			this.finish();
			return;
		}

		if		(state ==1)		waitForAnswer();
		else if (state ==2) 	getRealExtract();
		else if (state ==3) 	getExtractAndAskTranslate();

	}

	@Override
	public void onTTSAborted() {
		Log.d("DEBUGTAG","Le TTS a été aborted");
		Toast.makeText(this, "Un problème vient d'arriver, veuillez relancer l'exercice de répétition", Toast.LENGTH_LONG).show();
	}

	protected void onResume(){
		super.onResume();
		pttsPlayer = new ParrotTTSPlayer(this, this);
		state = 0;
		this.getExtractAndAskTranslate();
		
		if (wl == null){
			PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
	        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "whereisbryan");
	        wl.acquire();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		pttsPlayer.destroy();
		MP.getInstance().stop();
		if (this.currentAsync !=null)this.currentAsync.cancel(true);
		
		if (wl != null){
			wl.release();
			wl =null;
		}
		
	}
	@Override
	protected void onStop() {
		super.onStop();
		db.close();
		MP.getInstance().stop();
		if (this.currentAsync !=null)this.currentAsync.cancel(true);
		if (wl != null){
			wl.release();
			wl =null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_DPAD_UP) 
			MP.volumeDown(this, AudioManager.STREAM_MUSIC);
		else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) 
			MP.volumeUp(this, AudioManager.STREAM_MUSIC);
		return super.onKeyDown(keyCode, event);
	}


	@Override
	public void onCompletion(MediaPlayer mp) {
		this.currentAsync = new AsyncTask<Void, Void, Void>(){
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 1000);
				return null;
			}
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				pttsPlayer.play(e.getActorName()+" dans "+e.getMovieName()+".");

			}
		};
		this.currentAsync.execute();
	}
	
	
}
